/*
 * Copyright (C) 2009, Edmundo Albuquerque de Souza e Silva.
 *
 * This file may be distributed under the terms of the Q Public License
 * as defined by Trolltech AS of Norway and appearing in the file
 * LICENSE.QPL included in the packaging of this file.
 *
 * THIS FILE IS PROVIDED AS IS WITH NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

package model;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDomDriver;
import java.util.Enumeration;
import javax.swing.tree.TreeNode;
import util.GravarArquivo;
import util.ValidaItem;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author alexandre
 */
public class DAOIndex {

    IndexXML index = new IndexXML();
    main_class main = new main_class();
    TreeNode treeNode;
    private String titulo;
    private String subTitulo;
    private String destino;
    boolean resp;
    boolean flag = true;
    int aux = 0;
    private String xml;
    private static String msgn = "";
    private String topicoAux = "";

    public boolean gravarTopicos(TreeNode treeNode1, String titulo, String subTitulo, String destino, String textoRoot, int NumeroAula) {
        this.treeNode = treeNode1;
        this.destino = destino;


        if (!treeNode.toString().equals(textoRoot)) {
            Ind_item item = new Ind_item();
//                verifica formacao do item
            if (!ValidaItem.validar(treeNode.toString())) {
                msgn += treeNode.toString();
                flag = false;
                return false;
            }



            item.setText(treeNode.toString().substring(treeNode.toString().indexOf("-") + 1).trim());
            topicoAux = treeNode.toString();
            item.setTime(formatarTempo(treeNode.toString().substring(0, treeNode.toString().indexOf("-")).trim()));


            if (treeNode.getChildCount() > 0) {
                buscarFilho(treeNode, item);
                if (!this.treeNode.isLeaf()) {
                    Enumeration filho = treeNode.children();
                    treeNode = (TreeNode) filho.nextElement();
                }
            }

            index.setInd_item(item);
        }

        //recursividade
        for (Enumeration filho = treeNode.children(); filho.hasMoreElements();) {

            gravarTopicos((TreeNode) filho.nextElement(), titulo, subTitulo, this.destino, textoRoot, NumeroAula);

// ################## gerando o xml
            if (filho.hasMoreElements() == false) {
                index.setMain(main);
                index.setMain_title(titulo);
                main.setSub_title(subTitulo);
                main.setNumber(NumeroAula);

                //criando o XML e formatando underline simples
                XStream xstream = new XStream(new XppDomDriver(new XmlFriendlyReplacer("_-", "_")));
                // setando o nome da tag principal
                xstream.alias("index", IndexXML.class);
                xstream.alias("ind_item", Ind_item.class);

                //definindo o nome da tag
                xstream.aliasField("class", IndexXML.class, "mainClass");
                //omitindo a tag root Ind_item
                xstream.addImplicitCollection(IndexXML.class, "ind_item");
                xstream.addImplicitCollection(Ind_item.class, "ind_item");

                xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE index SYSTEM \"index.dtd\">\n" + xstream.toXML(index);

//                if (flag != false) {
//                    flag = GravarArquivo.salvarArquivo(getXml(), this.destino + ".index");
//                }

            }
        }
        return flag;
    }

// método recursivo para tratar os filhos
    private void buscarFilho(TreeNode treeNode, Ind_item item) {
        for (int i = 0; i < treeNode.getChildCount(); i++) {
            if (!ValidaItem.validar(treeNode.toString())) {
                msgn += treeNode.toString();
                flag = false;
                return;
            }
            TreeNode filho = treeNode.getChildAt(i);
            Ind_item item1 = new Ind_item();
            item1.setText(filho.toString().substring(filho.toString().indexOf("-") + 1).trim());
            //           guardando o valor do nó para a msg, se houver erro
            topicoAux = filho.toString();
            item1.setTime(formatarTempo(filho.toString().substring(0, filho.toString().indexOf("-")).trim()));

            item.setInd_item(item1);

            if (filho.getChildCount() > 0) {
                buscarFilho(filho, item1);
                if (!this.treeNode.isLeaf()) {
                    Enumeration filho1 = this.treeNode.children();
                    this.treeNode = (TreeNode) filho1.nextElement();
                }
            }
        }
//        Enumeration filho1 = treeNode.children();
//        this.treeNode = (TreeNode) filho1.nextElement();
    }

    /**
     * @param titulo the titulo to set
     */
    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    /**
     * @param subTitulo the subTitulo to set
     */
    public void setSubTitulo(String subTitulo) {
        this.subTitulo = subTitulo;
    }

    public String formatarTempo(String tempo) {

        int minutos = Integer.parseInt(tempo.substring(3, 5));
        minutos = (minutos * 60) + Integer.parseInt(tempo.substring(6));

        if (minutos < aux) {
            msgn += topicoAux + "\n";
            flag = false;
        }
        aux = minutos;
        return minutos + "";
    }

    /**
     * @return the xml
     */
    public String getXml() {
        return xml;
    }

    /**
     * @return the msgn
     */
    public static String getMsgn() {
        return msgn;
    }

    /**
     * @param msgn the msgn to set
     */
    public static void setMsgn(String msgn) {
        DAOIndex.msgn = msgn;
    }
}
